﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using WP.Commons;
using WP.DB;
using WP.Modules;
using WP.Controls;
using WP.Controls.GridColumn;


using WP.RM.BusinessRule;
using WP.RM.BusinessLogical;
using WP.RM.DataAccess;
namespace WP.RM.Form
{
    public partial class frmRMWorkQtyInputHdrMtn : BaseMtn
    {
        private bool[] mDtlColumnReadOnlyArray;
        private bool m_bCanTrigerCellValueChangedEven =false ;
        private bool mblnAbleToPostWorkQty = false;
        private string mstrTableName = "rmWorkQtyInputDtl";
        private System.Windows.Forms.DataGridView.HitTestInfo mhtiDtl = null;
        private bool m_bSettingStatus = false;
        private bool mPressExit = false;
        private enum DtlCol
        {
            RowSeqNo=0, HdrRecID, WorkerRecID, WorkerID,
            WorkerName, NamePY, WorkPositionSeqNo,WorkPositionName,
            WKPriceType, UnitCost, Qty, Remark,
            RecID, ValueChanged, DelButton 
        }

        public frmRMWorkQtyInputHdrMtn()
        {
            InitializeComponent();
            LoadAllControl(new ArrayList(this.Controls));
            this.MtnTabControl = this.tbcMain;
            this.DesignTabsName = "tbpGeneral";
            tbcMain.DrawMode = TabDrawMode.OwnerDrawFixed;
            this.MinimumSize = this.Size;
            InitGridDtl();
        }

        
        #region Define Variable
        private bool mblnSettingStatus = false;
        #endregion

        #region ***Form Events

        private void frmRMWorkQtyInputMtn_Load(object sender, EventArgs e)
        {
            this.TableName = "rmWorkQtyInputHdr";
            //dgList.ColumnWidth = "0,70,180,100,40,20,120,90,130";
            dgList.ConnectionString = DBAccess.ConnectionDBString;
            dgList.TableName = this.TableName;
            dgList.ColumnWidth = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgList.Name);
            string strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            dgList.Sql = strSql;
            this.formStatus = FormStatus.Query;
            initControl();
            FillLookUpInfo();
            FillTree();

            mblnAbleToPostWorkQty =CvtFunc.ToBoolean(  DataFunctions.GetFieldValue("mUser","AbleToPostWorkQty","UserName='"+ SysVar.UserName +"'"));  
            
        }
        private void frmRMWorkQtyInputMtn_FormClosing(object sender, FormClosingEventArgs e)
        {
            DataFunctions.SetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.dgList);
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!this.UpdateData()) return;
            
            if (this.dgvInputDtl.CurrentRow !=null )
            {
                if (!Update_Detail(this.dgvInputDtl.CurrentRow)) return;
            }
            if (!this.ConfirmSalary())
            {
                return;
            }
            base.SetStatusAfterUpdate();
        }
        private void btnNew_Click(object sender, EventArgs e)
        {
            if (this.ConfirmChange())
            {
                if (!this.UpdateData()) return;
            }
            this.formStatus = FormStatus.AddNew;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!this.DeleteData()) return;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.formStatus = FormStatus.Delete;
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
            {
                if (this.ConfirmChange())
                {
                    if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (!this.UpdateData()) return;
                    }
                }
            }
            this.ExitingStatus = true;
            this.Close();
        }
        private void btnHelp_Click(object sender, EventArgs e)
        {
            base.OnHelp();
        }
        private void btnToExcel_Click(object sender, EventArgs e)
        {
            base.ExportToExcel(dgList);
        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Next);
        }
        private void btnPrev_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Prev);
        }
        private void btnTop_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Top);
        }
        private void btnBottom_Click(object sender, EventArgs e)
        {
            Nevigate(this.dgList, NavigateOrient.Bottom);
        }
        public override void SetNavigatorBarTooltip()
        {
            if (this.RecID <= 0)
            {
                this.btnBottom.ToolTipText = "定位到末页";
                this.btnTop.ToolTipText = "定位到首页";
                this.btnNext.ToolTipText = "定位到下一页";
                this.btnPrev.ToolTipText = "定位到前一页";
            }
            else
            {
                this.btnBottom.ToolTipText = "定位到末记录";
                this.btnTop.ToolTipText = "定位到首记录";
                this.btnNext.ToolTipText = "定位到下一条记录";
                this.btnPrev.ToolTipText = "定位到上一条记录";
            }
        }

        private void dgList_DefineColumn(object sender, EventArgs e)
        {
            base.SelectListViewField(dgList);
        }
        private void dgList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && dgList.CurrentRow != null)
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }
        private void dgList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (dgList.CurrentRow != null && BaseFunctions.IsDataGridCell(this.dgList, e))
            {
                this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }

        protected override void Field_Leave(object sender, System.EventArgs e)
        {
            base.Field_Leave(sender, e);
            Control con = sender as Control;
            if (con == null) return;

            //below is some speci field , need do some speci work
            if (con.Name == txtWorkShopSeqNo.Name)
            {
            }
        }
        protected override void Field_Change(object sender, EventArgs e)
        {
            base.Field_Change(sender, e);
            if (this.formStatus == FormStatus.Delete) return;
            Control con = sender as Control;
            if (con == null) return;
            if (this.formStatus == FormStatus.AddNew)
            {
                if (con.Name == txtWorkShopSeqNo.Name)
                {
                    string strWKType = txtWorkShopSeqNo.Text;
                    if (strWKType.Length > 3) strWKType = strWKType.Substring(0, 3);

                    txtWorkShopName.Text = DataFunctions.GetFieldValue("rmWorkShop", "WorkShopName", "WorkShopSeqNo='" + strWKType + "'");
                }
            }
        }
        protected override void Field_KeyPress(object sender, KeyPressEventArgs e)
        {
            base.Field_KeyPress(sender, e);
        }

        private void tbcMain_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if ((this.formStatus == FormStatus.Query || this.formStatus == FormStatus.Delete) &&
                this.dgList.Rows.Count == 0 && e.TabPageIndex > 0)
            {
                e.Cancel = true;
                return;
            }

            if (e.TabPageIndex == 0)
            {
                if (this.formStatus == FormStatus.AddNew || this.formStatus == FormStatus.Update)
                {
                    if (this.ConfirmChange())
                    {
                        if (MessageBox.Show(SysVar.SaveChangeTitle, SysVar.WarnTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            if (!this.UpdateData())
                            {
                                if (m_bTabPageNeedCancel)
                                    e.Cancel = true;

                                m_bTabPageNeedCancel = true;
                                return;
                            }
                        }
                    }
                    this.formStatus = FormStatus.Delete;
                }
                else if (this.formStatus == FormStatus.Query)
                {
                    this.formStatus = FormStatus.Delete;
                }
                this.dgList.RefreshData();
                this.dgList.Focus();
            }
            else if (e.TabPageIndex != 0 && this.formStatus != FormStatus.AddNew)
            {
                if (this.RecID == -1)
                    this.RecID = Convert.ToInt64(dgList.RecID);
            }
        }
        private void tbcMain_DrawItem(object sender, DrawItemEventArgs e)
        {
            BaseFunctions.TabControl_DrawItem(sender, e, true);
        }
        private void FileMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mnuItem = sender as ToolStripMenuItem;
            if (mnuItem != null)
            {
                switch (mnuItem.Name)
                {
                    case "newToolStripMenuItem":
                        btnNew_Click(sender, e);
                        break;
                    case "cancelToolStripMenuItem":
                        btnCancel_Click(sender, e);
                        break;
                    case "deleteToolStripMenuItem":
                        btnDelete_Click(sender, e);
                        break;
                    case "saveToolStripMenuItem":
                        btnUpdate_Click(sender, e);
                        break;
                    case "exitToolStripMenuItem":
                        btnExit_Click(sender, e);
                        break;
                }
            }
        }

        #endregion Form Events***

        #region ***Form Functions

        public override bool DeleteData()
        {
            bool bUpdateResult = true;           
            bUpdateResult = base.DeleteData();            
            return bUpdateResult;
        }

        public override bool UpdateData()
        {
            bool bUpdateResult = true;
            if (!CheckQty()) return false ;
            if (base.ConfirmChange())
            {
                bUpdateResult = base.UpdateData();
            }
            return bUpdateResult;
        }
        public override bool ConfirmChange()
        {
            return (base.ConfirmChange());
        }
        protected override bool FieldCheck(string strFieldValue, string strFieldName, ref string strErrPrompt)
        {

            strErrPrompt = string.Empty;
            DBAccess dBAccess = new DBAccess(false, false);
            DataRow dr = base.GetCurrentMtnDataRow();


            RM.BusinessRule.RMWorkQtyInputHdrBRL mBRL = new WP.RM.BusinessRule.RMWorkQtyInputHdrBRL();
            bool bCheckResult = mBRL.FieldCheck(dBAccess, dr, strFieldName, ref strErrPrompt, this.formStatus);
            dBAccess.CloseCon();
            return bCheckResult;

        }
        protected override string GetLookUpSQL(string strTableName, string strLookUpControlName)
        {
            string strSql = string.Empty;
            return base.GetLookUpSQL(strTableName, strLookUpControlName);
        }
        public override void SetButtonStatus()
        {
            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.btnRecalWKUnitCost.Enabled = false;
                    break;
                case FormStatus.Delete:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = (true && this.CurrentMenuInfo.strPermit == "Y");
                    this.btnCancel.Enabled = false;
                    this.btnRecalWKUnitCost.Enabled = true;
                    break;
                case FormStatus.Query:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnNew.Enabled = (true && this.CurrentMenuInfo.strPermit == "Y");
                    this.btnCancel.Enabled = false;
                    this.btnRecalWKUnitCost.Enabled = true;
                    break;
                case FormStatus.Update:
                    BaseFunctions.ControlEnabled(this.toolStrip, false);
                    this.btnUpdate.Enabled = true;
                    this.btnDelete.Enabled = true;
                    this.btnNew.Enabled = true;
                    this.btnCancel.Enabled = true;
                    break;
                case FormStatus.Loading:
                    break;

            }

            this.btnToExcel.Visible = (this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query) && SysVar.AbleToExcel;
            this.btnToExcel.Enabled = this.formStatus == FormStatus.Delete || this.formStatus == FormStatus.Query;

            newToolStripMenuItem.Enabled = btnNew.Enabled;
            cancelToolStripMenuItem.Enabled = btnCancel.Enabled;
            deleteToolStripMenuItem.Enabled = btnDelete.Enabled;
            saveToolStripMenuItem.Enabled = btnUpdate.Enabled;
            

            if (this.formStatus == FormStatus.Update)
            {
                btnPost.Enabled = mblnAbleToPostWorkQty;
            }
            else
            {
                btnPost.Enabled = false;
            }

            this.btnTop.Enabled = true;
            this.btnBottom.Enabled = true;
            this.btnPrev.Enabled = true;
            this.btnNext.Enabled = true;
            this.btnHelp.Enabled = true;
            this.btnExit.Enabled = true;
        }
        public override void SetOtherStatus()
        {
            mblnSettingStatus = true;

            switch (this.formStatus)
            {
                case FormStatus.AddNew:
                    this.txtWorkShopSeqNo.Focus();
                    break;
                case FormStatus.Delete:
                    break;
                case FormStatus.Query:
                    break;
                case FormStatus.Update:
                    break;
                case FormStatus.Loading:
                    break;
            }

            mblnSettingStatus = false;
        }

        protected override void ShowOtherData()
        {
            base.ShowOtherData();
            FillDtl(); 
        }

        public override void RefreshOverView()
        {
            base.RefreshOverView();
            if (this.RecID != -1)
                this.dgList.RecID = this.RecID;
        }

        private void FillLookUpInfo()
        {
            SetFieldLookUpInfo("WorkShopSeqNo", "rmWorkShop", "WorkShopSeqNo", "ubtWorkShopSeqNo");
            SetFieldLookUpInfo("WorkShopName", "rmWorkShop", "WorkShopName", "ubtWorkShopSeqNo");

            SetFieldLookUpInfo("WorkGroupSeqNo", "rmWorkGroup", "SeqNo", "ubtWorkGroupSeqNo");
            SetFieldLookUpInfo("WorkGroupName", "rmWorkGroup", "WorkGroupName", "ubtWorkGroupSeqNo");

            SetFieldLookUpInfo("WorkingProcedureID", "rmWorkingProcedure", "WorkingProcedureID", "ubtWorkingProcedureID");
            SetFieldLookUpInfo("WorkingProcedureName", "rmWorkingProcedure", "WorkingProcedureName", "ubtWorkingProcedureID");

            SetFieldLookUpInfo("ProductFItemID", "rmProduct", "ProductFItemID", "ubtProductFItemID");
            SetFieldLookUpInfo("ProductID", "rmProduct", "ProductID", "ubtProductFItemID");
            SetFieldLookUpInfo("ProductName", "rmProduct", "ProductName", "ubtProductFItemID");

            SetFieldLookUpInfo("SemiCode", "imSemiProduct", "SemiCode", "ubtSemiCode");

            SetFieldLookUpInfo("MachineSeqNo", "rmMachine", "MachineSeqNo", "ubtMachineSeqNo");

            SetFieldLookUpInfo("Unit", "imUnit", "Unit", "ubtUnit");
        }

        #endregion Form Functions***

        private void tvTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Nodes.Count == 0) //最后一层
            {
                string strMaterialID = "";
                strMaterialID = CvtFunc.ToString(e.Node.Text.ToString()).Split('-')[0];
                //this.dgList.FindRecord(strMaterialID, "MaterialTypeID");
                string strCond = " WorkShopSeqNo like '" + strMaterialID + "%'";
                ShowOverViewGrid(strCond);
            }
        }

        
        public override void InitDeftValue()
        {
            base.InitDeftValue();
            if (tvTree.SelectedNode != null)
            {
                txtWorkShopSeqNo.Text = CvtFunc.ToString(tvTree.SelectedNode.Text).Split('-')[0];
                txtWorkShopName.Text = CvtFunc.ToString(tvTree.SelectedNode.Text).Split('-')[1]; 
            }
        }

        

        private void FillTree()
        {
            DBAccess dbcon = new DBAccess(false, false);
            string strSQL = "select WorkShopSeqNo,WorkShopName from rmWorkShop order by WorkShopSeqNo";
            DataTable dtItem = dbcon.GetDataTable(strSQL);
            foreach (DataRow drType in dtItem.Rows)
            {
                TreeNode tvNode = new TreeNode(CvtFunc.ToString(drType["WorkShopSeqNo"]) + "-" + CvtFunc.ToString(drType["WorkShopName"]));
                this.tvTree.Nodes.Add(tvNode);
            }
            dbcon.CloseCon();
        }

        private void ShowOverViewGrid(string strWhereCondition)
        {
            string strSql = "";
            if (dgList.Sql.Trim() == "")
                strSql = WP.Commons.BaseFunctions.GetLookUpSQL(this.TableName, this.CurrentMenuInfo.iParameter);
            else
                strSql = dgList.Sql;

            if (strWhereCondition != "")
            {
                string strOrderBy = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartOrderBy);
                strSql = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartMain) + " where " + strWhereCondition;
                strSql += strOrderBy;
            }
            //string strWhere = BaseFunctions.GetSqlParts(strSql, SqlOption.SqlPartWhere);
            //mstrWhereCondition = strWhere;
            this.dgList.Sql = strSql;
        }




        #region Input Detail GRID

        private void InitGridDtl()
        {
            // RecID  HdrRecID WorkerRecID WorkerID WorkerName NamePY WorkPositionSeqNo WKPriceType UnitCost Qty
            this.dgvInputDtl.Columns.Clear();
            this.dgvInputDtl.Rows.Clear();

            DataGridViewTextBoxColumn colRowSeqNo = new DataGridViewTextBoxColumn();
            colRowSeqNo.HeaderText = "序号";
            colRowSeqNo.Visible = true;
            colRowSeqNo.Name = "RowSeqNo";
            colRowSeqNo.Width = 50;
            colRowSeqNo.ReadOnly = true;
            colRowSeqNo.SortMode = DataGridViewColumnSortMode.NotSortable;

            DataGridViewTextBoxColumn colHdrRecID = new DataGridViewTextBoxColumn();
            colHdrRecID.HeaderText = "表头ID";
            colHdrRecID.Width = 70;
            colHdrRecID.Name = "HdrRecID";
            colHdrRecID.ReadOnly = false;
            colHdrRecID.Visible = false ;

            TextLookUpColumn colWorkerRecID = new TextLookUpColumn();
            colWorkerRecID.HeaderText = "员工RecID";
            colWorkerRecID.Width = 100;
            colWorkerRecID.Name = "WorkerRecID";
            colWorkerRecID.ReadOnly = true;
            colWorkerRecID.Visible = false ;

            DataGridViewTextBoxColumn colWorkerID = new DataGridViewTextBoxColumn();
            colWorkerID.HeaderText = "员工代码";
            colWorkerID.Width = 100;
            colWorkerID.Name = "WorkerID";
            colWorkerID.ReadOnly = true;
            colWorkerID.Visible = false;

            TextLookUpColumn colWorkerName = new TextLookUpColumn();
            colWorkerName.HeaderText = "员工姓名";
            colWorkerName.Width = 100;
            colWorkerName.Name = "WorkerName";
            colWorkerName.ReadOnly = false;
            colWorkerName.Visible = true;

            DataGridViewTextBoxColumn colNamePY = new DataGridViewTextBoxColumn();
            colNamePY.HeaderText = "拼音简码";
            colNamePY.Width = 100;
            colNamePY.Name = "NamePY";
            colNamePY.ReadOnly = false;
            colNamePY.Visible = true;

            //WorkPositionSeqNo WorkPositionName WKPriceType UnitCost Qty
            TextLookUpColumn colWorkPositionSeqNo = new TextLookUpColumn();
            colWorkPositionSeqNo.HeaderText = "岗位序号";
            colWorkPositionSeqNo.Width = 70;
            colWorkPositionSeqNo.Name = "WorkPositionSeqNo";
            colWorkPositionSeqNo.ReadOnly = false;
            colWorkPositionSeqNo.SortMode = DataGridViewColumnSortMode.Automatic;

            TextLookUpColumn colWorkPositionName = new TextLookUpColumn();
            colWorkPositionName.HeaderText = "岗位名称";
            colWorkPositionName.Width = 100;
            colWorkPositionName.Name = "WorkPositionName";
            colWorkPositionName.ReadOnly = true ;
            colWorkPositionName.SortMode = DataGridViewColumnSortMode.Automatic;


            //WKPrictType,         //工价类别
            DataGridViewTextBoxColumn colWKPrictType = new DataGridViewTextBoxColumn();
            colWKPrictType.HeaderText = "工价类别";
            colWKPrictType.Width = 100;
            colWKPrictType.Name = "WKPriceType";
            colWKPrictType.ReadOnly = false;
            colWKPrictType.Visible  = true ;

            //UnitCost,         //计件工价
            DataGridViewTextBoxColumn colUnitCost = new DataGridViewTextBoxColumn();
            colUnitCost.HeaderText = "计件工价";
            colUnitCost.Width = 100;
            colUnitCost.Name = "UnitCost";
            colUnitCost.ReadOnly = false;
            colUnitCost.Visible = true ;
            colUnitCost.DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomRight;
            colUnitCost.HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomRight;    

            //Qty,         //数量
            DataGridViewTextBoxColumn colQty = new DataGridViewTextBoxColumn();
            colQty.HeaderText = "产量";
            colQty.Width = 100;
            colQty.Name = "Qty";
            colQty.ReadOnly = false;
            colQty.Visible = true;
            colQty.DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomRight;
            colQty.HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomRight;
            //Remark,         //备注
            DataGridViewTextBoxColumn colRemark = new DataGridViewTextBoxColumn();
            colRemark.HeaderText = "备注";
            colRemark.Width = 100;
            colRemark.Name = "Remark";
            colRemark.ReadOnly = false;
            colRemark.Visible = true;

            DataGridViewTextBoxColumn colRecID = new DataGridViewTextBoxColumn();
            colRecID.HeaderText = "RecID";
            colRecID.Visible = false;
            colRecID.Name = "RecID";

            DataGridViewTextBoxColumn colValueChanged = new DataGridViewTextBoxColumn();
            colValueChanged.HeaderText = "ValueChanged";
            colValueChanged.Visible = false;
            colValueChanged.Name = "ValueChanged";

            DataGridViewImageColumn colDel = new DataGridViewImageColumn();
            Bitmap delbitmap = new Bitmap(this.iglSource.Images["del.ico"]);
            colDel.Width = 20;
            colDel.Name = "DelLine";
            colDel.HeaderText = "";
            colDel.Resizable = DataGridViewTriState.False;

            //RecID  HdrRecID WorkerRecID WorkerID WorkerName NamePY WorkPositionSeqNo WKPriceType UnitCost Qty
            this.dgvInputDtl.Columns.AddRange(new DataGridViewColumn[] { colRowSeqNo, colHdrRecID, colWorkerRecID, colWorkerID,
                                                                         colWorkerName, colNamePY,colWorkPositionSeqNo, colWorkPositionName,
                                                                         colWKPrictType, colUnitCost,colQty,colRemark,
                                                                         colRecID, colValueChanged, colDel });

            mDtlColumnReadOnlyArray = new bool[dgvInputDtl.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgvInputDtl.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgvInputDtl.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray[i] = dgvInputDtl.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgvInputDtl.Columns.Count) dgvInputDtl.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
            }

            this.dgvInputDtl.EditMode = DataGridViewEditMode.EditOnEnter;
            this.dgvInputDtl.RowTemplate.Height = 20;
            this.dgvInputDtl.RowHeadersWidth = 23;
            this.dgvInputDtl.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.dgvInputDtl.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            this.dgvInputDtl.ColumnHeadersHeight = 30;
            this.dgvInputDtl.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgvInputDtl.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.dgvInputDtl.AllowUserToResizeRows = false;

        }
        private void FillDtl()
        {
            string strSql = "";
            string strUserName = "";
            string strRecid = "";
            bool bAccess = false;
            m_bCanTrigerCellValueChangedEven = false;

            this.dgvInputDtl.Rows.Clear();
            DBAccess dbCon = new DBAccess(false, false);

            strSql = "select * from "+ mstrTableName +" where hdrrecid ='"+ this.m_lRecId +"'";
            DataTable mUserAlertTable = dbCon.GetDataSet(strSql).Tables[0];

            for (int i = 0; i < mUserAlertTable.Rows.Count; i++)
            {
                DataRow dr = mUserAlertTable.Rows[i];
                if (this.dgvInputDtl.Rows.Count <= i) this.dgvInputDtl.Rows.Add();
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.RowSeqNo].Value = dgvInputDtl.Rows.Count.ToString();
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.HdrRecID].Value = this.m_lRecId.ToString()  ;
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.NamePY].Value = dbCon.GetValue ("select namepy from rmWorker where recid='"+ dr["WorkerRecID"] +"'");
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.Qty].Value =BaseFunctions.FormatNumeric(dr["Qty"], "ns.0");
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.RecID].Value = dr["RecID"].ToString().TrimEnd();
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.UnitCost].Value = dr["UnitCost"].ToString().TrimEnd();

                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.WKPriceType].Value = CvtFunc.ToString(dr["WKPriceType"].ToString());
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.WorkerID].Value = dbCon.GetValue("select WorkerID from rmWorker where recid='" + dr["WorkerRecID"] + "'");
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.WorkerName ].Value = dbCon.GetValue ("select WorkerName from rmWorker where recid='"+ dr["WorkerRecID"] +"'");


                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.WorkerRecID ].Value =dr["WorkerRecID"];
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.WorkPositionName].Value = dbCon.GetValue("select WorkPositionName from rmWorkPosition where WorkPositionSeqNo='" + dr["WorkPositionSeqNo"] + "'");
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.WorkPositionSeqNo].Value = dr["WorkPositionSeqNo"].ToString();
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.Remark].Value = dr["Remark"]; 
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.RecID].Value = CvtFunc.ToInt(dr["RecID"]);
                dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.ValueChanged].Value = "0";
            }//
            if (dgvInputDtl.Rows.Count == 0)
            {
                AddDtlRow(this.dgvInputDtl.Name);
            }
            dbCon.CloseCon();          
            base.SetBlankImage(dgvInputDtl);
            m_bCanTrigerCellValueChangedEven = true;
        }
        private void dgvDetail_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (dgvInputDtl.Columns[e.ColumnIndex] is TextLookUpColumn)
            {
                if ((dgvInputDtl.Columns[e.ColumnIndex] as TextLookUpColumn).CanLookUp())
                {
                    Dtl_LookUp(e.ColumnIndex);
                }
            }
            else
            {
                if (this.dgvInputDtl.CurrentCell.ColumnIndex == (int)DtlCol.DelButton && base.HasDelImage(this.dgvInputDtl, e))
                {
                    this.dgvInputDtl.CurrentCell.Selected = true;
                    this.dgvInputDtl.CurrentCell.Selected = false;
                    if (!this.Delete_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex]))
                    {
                        return;
                    }
                    this.dgvInputDtl.Rows.Remove(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex]);
                    if (this.dgvInputDtl.Rows.Count == 0)
                    {
                        this.AddDtlRow(this.dgvInputDtl.Name);
                    }
                }
            }
        }


        private void initControl()
        {
            cmbCalType.Items.Clear(); 
            cmbCalType.Items.Add("0 -- 求和");
            cmbCalType.Items.Add("1 -- 平均");
        }

        private void AddDtlRow(string strGridName)
        {
            AddDtlRow(strGridName, -1);
        }

        private void AddDtlRow(string strGridName, double iRow)
        {
            if (strGridName == dgvInputDtl.Name)
            {
                int intRow = CvtFunc.ToInt(iRow);
                m_bCanTrigerCellValueChangedEven = false;
                if (iRow >= 0)
                {
                    intRow++;
                    this.dgvInputDtl.Rows.Insert(intRow, 1);
                }
                else
                {
                    this.dgvInputDtl.Rows.Add();
                    intRow = this.dgvInputDtl.Rows.Count - 1;
                }
                dgvInputDtl.Rows[intRow].Cells["RowSeqNo"].Value = dgvInputDtl.Rows.Count.ToString();
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.HdrRecID].Value = this.m_lRecId.ToString() ;
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.NamePY].Value = "";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.Qty].Value = "0";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.UnitCost].Value = "0.00";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WKPriceType].Value ="";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WorkerID].Value = "0";

                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WKPriceType].Value = "";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WorkerName].Value = "";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WorkerID].Value = "";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WorkPositionName].Value = "";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WorkPositionSeqNo].Value = "";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.Remark].Value = "";
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.RecID].Value = -1;
                dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.ValueChanged].Value = "0";
                dgvInputDtl.CurrentCell = dgvInputDtl.Rows[intRow].Cells[(int)DtlCol.WorkerName];
                m_bCanTrigerCellValueChangedEven = true;
            }
        }

        protected override void ubtLookUp_Click(object sender, EventArgs e)
        {
            Control con = sender as Control;
            if (con.Name == ubtProductFItemID.Name)
            {
                string strSQL = BaseFunctions.GetLookUpSQL("rmProduct");
                frmLookUpProduct frmlookup = new frmLookUpProduct(strSQL, "产成品选择", con.Text, "ProductName");
                frmlookup.ShowDialog();
                if (frmlookup.HaveReturnValue)
                {
                    txtProductName.Text = frmlookup.GetReturnValue("ProductName");
                    txtProductID.Text = frmlookup.GetReturnValue("ProductID");
                    txtProductFItemID.Text = frmlookup.GetReturnValue("ProductFItemID");                   
                }
                frmlookup.Close();
            }
            else if (con.Name == ubtSemiCode.Name)
            {
                using (DBAccess dbcon = new DBAccess(false, false))
                {
                    frmRMSelProductSemi frmlookup = new frmRMSelProductSemi(dbcon , "半成品选择", txtProductFItemID.Text);
                    frmlookup.ShowDialog();
                    if (frmlookup.HaveReturnValue)
                    {
                        string strReturn = CvtFunc.ToString ( frmlookup.tvSemi.SelectedNode.Tag) ;
                  
                        txtSemiRecID.Text = strReturn;
                        
                        string[] strSemi = CvtFunc.ToString(frmlookup.tvSemi.SelectedNode.Text).Split(new string[] { "-" }, StringSplitOptions.None);
                        if (strSemi.Length == 2)
                        {
                            string strSemiCode = strSemi[0];
                            string strSemiName = strSemi[1];
                            txtSemiCode.Text = strSemiCode;
                            txtSemiName.Text = strSemiName;
                        }
                    }
                    frmlookup.Close();
                }
            }
            else
            {
                base.ubtLookUp_Click(sender, e);
            }
        }

        private void Dtl_LookUp(int iColumnIndex)
        {
            string strSQL = "", strCaption = "", strFindValue = "", strFindField = "";
            switch ((DtlCol)iColumnIndex)
            {
                case DtlCol.WorkerName:
                    strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmWorker");
                    strCaption = "员工工号";
                    if (this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value != null) strFindValue = this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value.ToString();
                    strFindField = "WorkerID";
                    break;
                case DtlCol.WorkPositionSeqNo:
                    strSQL = WP.Commons.BaseFunctions.GetLookUpSQL("rmWorkPosition");
                    strCaption = "岗位";
                    if (this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkPositionSeqNo].Value != null) strFindValue = this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkPositionSeqNo].Value.ToString();
                    strFindField = "WorkPositionSeqNo";
                    break ;
            }

            if (strSQL == "") return;
            if (mblnLookUpSortByDescription)
            {
                strSQL = DataFunctions.GetSqlByDescriptionSort(strSQL);
                mblnLookUpSortByDescription = false;
            }

            frmLookUp frmlookup = new frmLookUp(strSQL, strCaption, strFindValue, strFindField);
            frmlookup.ShowDialog();

            if (frmlookup.HaveReturnValue)
            {
                switch ((DtlCol)iColumnIndex)
                {
                    case DtlCol.WorkerName:
                        this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value = frmlookup.GetReturnValue("WorkerID");
                        this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerRecID].Value = frmlookup.GetReturnValue("RecID");
                        this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value = frmlookup.GetReturnValue("WorkerName");
                        break;
                    case DtlCol.WorkPositionSeqNo:
                        this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkPositionSeqNo].Value = frmlookup.GetReturnValue("WorkPositionSeqNo");
                        this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkPositionName].Value = frmlookup.GetReturnValue("WorkPositionName");                        
                        break;
                }
                GetWorkerInfoByWorkerID( CvtFunc.ToString ( this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value),iColumnIndex);
            }
            frmlookup.Close();
        }

        private void GetWorkerInfoByWorkerID(string strWorkerID, int intCol)
        {
            string strSQL = "select * from rmWorker where WorkerID='" + strWorkerID + "'";
            DBAccess dbcon = new DBAccess(false, false);
            DataRow drWorkInfo = dbcon.GetDataFirstRow(strSQL);
            if (drWorkInfo != null)
            {
                if (intCol != (int)DtlCol.WorkPositionSeqNo)
                {
                    this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkPositionSeqNo].Value = CvtFunc.ToString(drWorkInfo["WorkPositionSeqNo"]);
                    this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkPositionName].Value = CvtFunc.ToString(drWorkInfo["WorkPositionName"]);
                }
                this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerRecID].Value = CvtFunc.ToString(drWorkInfo["RecID"]);
                this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value = CvtFunc.ToString(drWorkInfo["WorkerName"]);
                this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.NamePY].Value = CvtFunc.ToString(drWorkInfo["NamePY"]);
            }
            dbcon.CloseCon(); 
        }
        
        /// <summary>
        /// 通过工序和岗位获得工价类别，再获得计件工价
        /// </summary>
        /// <param name="strWorkPositionSeqNo"></param>
        /// <param name="strWorkingProcedureID"></param>
        private void  GetWKPriceTypeAndUnitCost(string strWorkPositionSeqNo, string strWorkingProcedureID, ref string strWKPriceType, ref string strUnitCost)
        {
            DBAccess dbcon = new DBAccess(false, false);
            string strSQL = "select * from imCategoryWKWorkCostPosition where WorkPositionSeqNo='{0}' and WKProductID='{1}'";
            strSQL = string.Format(strSQL, strWorkPositionSeqNo, strWorkingProcedureID);
            DataRow drWKPrice = dbcon.GetDataFirstRow(strSQL);
            if (drWKPrice != null)
            {
                strWKPriceType = CvtFunc.ToString(drWKPrice["WKPriceType"]);
                strUnitCost = CvtFunc.ToString(drWKPrice["WKUnitCost"]);
            }
            dbcon.CloseCon();
        }

        private bool CheckDtlRow(ref string strErrMsg)
        {
            bool bCheckResult = true;
            for (int i = 0; i < dgvInputDtl.ColumnCount - 1; i++)
            {

                bCheckResult = CheckDtlCell(i, ref strErrMsg);
                if (!bCheckResult) break;
            }
            if (CvtFunc.ToString(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value).Length ==0)
            {
                strErrMsg = "员工姓名不能为空";
                bCheckResult = false;
            }
            return bCheckResult;
        }
        private bool CheckDtlCell(int iColumn, ref string strErrMsg)
        {
            bool bReturnValue = true;
            strErrMsg = "";
            string strValue = "",strValue_WorkerRecID="";
            if (this.dgvInputDtl.CurrentRow != null && this.dgvInputDtl.CurrentRow.Cells[iColumn].Value != null)
            {
                strValue = CvtFunc.ToString ( this.dgvInputDtl.CurrentRow.Cells[iColumn].Value);
                strValue_WorkerRecID = CvtFunc.ToString ( this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerRecID].Value);
            }
            switch ((DtlCol)iColumn)
            {
                case DtlCol.WorkerName:
                    if (strValue.Trim() == "" && CvtFunc.ToString ( this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.NamePY].Value) !="")
                    {
                        strErrMsg = "员工姓名不能空.";
                        return false;
                    }
                    if (!DataFunctions.CheckRecordExist("rmWorker", strValue_WorkerRecID, "RecID") && CvtFunc.ToString(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.NamePY].Value) != "")
                    {
                        strErrMsg = "不存在的员工姓名";
                        return false;
                    }

                    return true;              
            }
            return bReturnValue;
        }
        private void dgvDetail_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (dgvInputDtl.CurrentRow == null)
            {
                e.Cancel = false;
                return;
            }
            if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0 && CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) == 0)
            {
                e.Cancel = false;
                return;

            }

            if (mhtiDtl != null && mhtiDtl.ColumnIndex == (int)DtlCol.DelButton)
            {
                mhtiDtl = null;
                return;
            }


            if (this.dgvInputDtl.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                e.Cancel = false;
                return;

            }
            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvInputDtl") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }

            e.Cancel = !CheckDtlCell(e.ColumnIndex, ref strErrMsg);
            if (mPressExit) { e.Cancel = false; return; };
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        private void dgvDetail_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (dgvInputDtl.CurrentRow != null && CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0 && CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) == 0)
            {
                e.Cancel = false;
                return;

            }

            string strErrMsg = "";
            if (!BaseFunctions.NeedValidGridCell(this.ActiveControl, "dgvInputDtl") || m_bSettingStatus || !m_bCanTrigerCellValueChangedEven)
            {
                e.Cancel = false;
                return;
            }
            e.Cancel = !CheckDtlRow(ref strErrMsg);
            if (mPressExit) { e.Cancel = false; return; };
            if (strErrMsg != "")
            {
                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }
        private void dgvDetail_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (!m_bCanTrigerCellValueChangedEven || e.ColumnIndex == (int)DtlCol.ValueChanged || e.ColumnIndex == (int)DtlCol.DelButton) return;
            dgvInputDtl.Rows[e.RowIndex].Cells[(int)DtlCol.ValueChanged].Value = "1";
            
            dgvInputDtl.EndEdit();
            DBAccess dbcon = new DBAccess(false, false);
            {
                if (e.ColumnIndex == (int)DtlCol.NamePY)
                {
                    string strNamePY = CvtFunc.ToString(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.NamePY].Value);
                    string strSQL = "select * from rmWorker where NamePY ='" + strNamePY + "'";
                    DataTable dtWorker = dbcon.GetDataTable(strSQL);
                    foreach (DataRow drWorker in dtWorker.Rows)
                    {
                        if (dtWorker.Rows.Count == 1)
                        {
                            this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value = drWorker["WorkerID"];
                            this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerRecID].Value = drWorker["RecID"];
                            this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value = drWorker["WorkerName"];
                        }
                        else if (dtWorker.Rows.Count == 0)
                        {

                        }
                        else if (dtWorker.Rows.Count > 1)
                        {
                            strSQL = BaseFunctions.GetLookUpSQL("rmWorker"); 
                            frmLookUp frmlookup = new frmLookUp(strSQL, "员工选择", strNamePY, "RecID");
                            frmlookup.ShowDialog();
                            if (frmlookup.HaveReturnValue)
                            {
                                this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerRecID].Value = frmlookup.GetReturnValue("RecID");
                                this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerID].Value = frmlookup.GetReturnValue("WorkerID");                                
                                this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkerName].Value = frmlookup.GetReturnValue("WorkerName");
                            }
                        }
                    }
                }
                else if (e.ColumnIndex == (int)DtlCol.WorkPositionSeqNo)
                {
                    string  strWKPriceType ="", strUnitCost="";
                    GetWKPriceTypeAndUnitCost(CvtFunc.ToString(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WorkPositionSeqNo].Value)
                                                   , txtWorkingProcedureID.Text, ref strWKPriceType, ref strUnitCost);
                    this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WKPriceType].Value = strWKPriceType;
                    this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.UnitCost].Value = BaseFunctions.FormatNumeric(strUnitCost, "ns.6");
                }
            }
            dbcon.CloseCon(); 
            dgvInputDtl.EndEdit();
        }
        private void dgvDetail_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvInputDtl.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvInputDtl.CurrentCell.Selected = false;
            }
            SetColReadOnly();
        }

        private void SetColReadOnly()
        {
           if (this.dgvInputDtl.CurrentCell.ColumnIndex ==(int)DtlCol.RowSeqNo
               || this.dgvInputDtl.CurrentCell.ColumnIndex ==(int)DtlCol.WorkPositionName
            )   
           {
               this.dgvInputDtl.CurrentCell.ReadOnly = true ;
           }
            else
            {
            this.dgvInputDtl.CurrentCell.ReadOnly = false;
            }
        }

        private void dgvDetail_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvInputDtl.CurrentCell.ColumnIndex == (int)DtlCol.DelButton)
            {
                this.dgvInputDtl.CurrentCell.Selected = false;
            }
        }
        private void dgvDetail_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            return;
        }
        private void dgvDetail_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            base.SetGridViewDelImage(this.dgvInputDtl, e, (int)DtlCol.DelButton);
            string strErrMsg = "";
            if (dgvInputDtl.CurrentRow != null && CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
            {
                if (CheckDtlRow(ref strErrMsg))
                {
                    if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex]))
                    {
                        return;
                    }

                    //AddDtlRow(this.dgvInputDtl.Name);
                }
                else
                {
                    return;
                }
            }
            
        }
        private void dgvDetail_MouseDown(object sender, MouseEventArgs e)
        {

            mhtiDtl = this.dgvInputDtl.HitTest(e.X, e.Y);

            //System.Windows.Forms.DataGridView.HitTestInfo hti;
            //hti = this.dgvInputDtl.HitTest(e.X, e.Y);
            //switch (hti.Type)
            //{
            //    case System.Windows.Forms.DataGridViewHitTestType.Cell:
            //        break;
            //}
        }
        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) //激活回车键
        {
            int WM_KEYDOWN = 256;
            int WM_SYSKEYDOWN = 260;
            if (!(msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN))
            {
                return false;
            }

            bool blnRet = false;
            if (BaseFunctions.TrigerKeyEventByControl(this.ActiveControl, this.dgvInputDtl.Name))
            {
                blnRet = dgvDetail_KeyDownEvent(keyData);
            }          

            if (!blnRet)
            {
                return base.ProcessCmdKey(ref msg, keyData);
            }
            return blnRet;
        }
        private bool dgvDetail_KeyDownEvent(System.Windows.Forms.Keys keyData)
        {
            string strErrMsg = "";
            int j;
            switch (keyData)
            {
                case Keys.Down:
                    #region Key Down

                    this.dgvInputDtl.EndEdit();
                    if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {

                            if (CheckDtlRow(ref strErrMsg))
                            {

                                if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex]))
                                {
                                    return true;
                                }
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvInputDtl.CurrentCell.RowIndex < dgvInputDtl.Rows.Count - 1)
                        {
                            dgvInputDtl.CurrentCell = this.dgvInputDtl.Rows[dgvInputDtl.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WorkerID];
                        }
                        else
                        {
                            AddDtlRow(this.dgvInputDtl.Name);
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex]))
                            {
                                return true;
                            }
                            AddDtlRow(this.dgvInputDtl.Name);
                        }
                        else
                        {
                            MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return true;
                        }
                    }
                    return true;


                    #endregion
                case Keys.Up:
                    #region Key Up
                    if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                    {
                        if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }
                        }
                        if (dgvInputDtl.CurrentCell.RowIndex > 0)
                        {
                            dgvInputDtl.CurrentCell = this.dgvInputDtl.Rows[dgvInputDtl.CurrentCell.RowIndex - 1].Cells[(int)DtlCol.RowSeqNo];
                        }
                    }
                    else
                    {
                        if (CheckDtlRow(ref strErrMsg))
                        {
                            if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex])) return true;
                            if (dgvInputDtl.CurrentCell.RowIndex > 0)
                            {
                                dgvInputDtl.CurrentCell = this.dgvInputDtl.Rows[dgvInputDtl.CurrentCell.RowIndex - 1].Cells[(int)DtlCol.RowSeqNo];
                            }
                        }
                        else if (dgvInputDtl.Rows.Count > 1)
                        {

                            this.dgvInputDtl.Rows.Remove(this.dgvInputDtl.CurrentRow);
                            dgvInputDtl.CurrentCell = this.dgvInputDtl.Rows[dgvInputDtl.Rows.Count - 1].Cells[(int)DtlCol.RowSeqNo];
                        }
                    }
                    return true;
                    #endregion
                case Keys.Enter:
                    #region Key Enter
                    this.dgvInputDtl.EndEdit();
                    j = BaseFunctions.GetGridViewLastEnabledEditColumn(this.dgvInputDtl);
                    if (dgvInputDtl.CurrentCell.ColumnIndex == j)
                    {
                        if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.RecID].Value) > 0)
                        {
                            if (CvtFunc.ToInt(dgvInputDtl.CurrentRow.Cells[(int)DtlCol.ValueChanged].Value) > 0)
                            {
                                if (CheckDtlRow(ref strErrMsg))
                                {
                                    if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex])) return true;
                                }
                                else
                                {
                                    MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    return true;
                                }
                            }
                        }
                        else
                        {
                            if (CheckDtlRow(ref strErrMsg))
                            {
                                if (!Update_Detail(this.dgvInputDtl.Rows[this.dgvInputDtl.CurrentCell.RowIndex])) return true;
                            }
                            else
                            {
                                MessageBox.Show(strErrMsg, SysVar.WarnTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return true;
                            }

                        }
                        if (dgvInputDtl.CurrentCell.RowIndex < dgvInputDtl.Rows.Count - 1)
                        {
                            dgvInputDtl.CurrentCell = this.dgvInputDtl.Rows[dgvInputDtl.CurrentCell.RowIndex + 1].Cells[(int)DtlCol.WorkerID];
                        }
                        else
                        {
                            AddDtlRow(this.dgvInputDtl.Name);
                        }
                    }
                    else
                    {
                        j = BaseFunctions.GetGridViewNextEnabledEditColumn(dgvInputDtl, dgvInputDtl.CurrentCell.ColumnIndex);
                        if (j >= 0) SendKeys.Send("{Tab}");
                        //  if (j >= 0) dgvInputDtl.CurrentCell = this.dgvInputDtl.Rows[dgvInputDtl.CurrentCell.RowIndex].Cells[j];
                    }

                    return true;
                    #endregion
            }
            return false;
        }

        private bool CheckQty()
        {
            double dblTotQty = 0;
            foreach (DataGridViewRow drvRow in this.dgvInputDtl.Rows)
            {
                dblTotQty += CvtFunc.ToDouble(drvRow.Cells[(int)DtlCol.Qty].Value);
            }
            if (cmbCalType.SelectedIndex == 0)
            {
                
            }
            else
            {
                dblTotQty = dblTotQty /CvtFunc.ToDouble ( txtWorkQty.Text); 
            }
            if (CvtFunc.ToDouble(txtWorkQty.Text, 0) - CvtFunc.ToDouble(dblTotQty, 0) <= 0)
            {
                return true;
            }
            MsgBoxEx.Show("请检查输入的数量。", SysVar.WarnTitle);
            return false;
        }

        private bool Update_Detail(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return false;
            string strSQL = string.Empty;
            this.dgvInputDtl.EndEdit();
            DBAccess dbcon = new DBAccess(false, false);
           
            try
            {
                DataRow drDtl = dbcon.GetDataTable("select * from " + mstrTableName + " ").NewRow();
                drDtl["HdrRecID"] = this.m_lRecId;
                if (CvtFunc.ToDouble(dgvRow.Cells[(int)DtlCol.RecID].Value) > 0)   //Update
                {
                    BaseFunctions.FillDataRowByGridRow(dgvRow, drDtl);
                    RMWorkQtyInputHdrDAL rmDAL = new RMWorkQtyInputHdrDAL();
                    rmDAL.UpdateDetail(dbcon, drDtl); 
                }
                else //Add New
                {
                    BaseFunctions.FillDataRowByGridRow(dgvRow, drDtl);
                    RMWorkQtyInputHdrDAL rmDAL = new RMWorkQtyInputHdrDAL();
                    rmDAL.AddDetail(dbcon, drDtl); 
                    dgvRow.Cells[(int)DtlCol.RecID].Value = CvtFunc.ToString(drDtl["RecID"]);
                }
                dbcon.CloseCon();
            }
            catch (Exception ex)
            {
                dbcon.CloseCon();
                return false;
            }
            return true;
        }
        private bool Delete_Detail(DataGridViewRow dgvRow)
        {
            if (dgvRow == null) return true;
            string strRecID = CvtFunc.ToString(dgvRow.Cells[(int)DtlCol.RecID].Value);
            string strSeqNo = CvtFunc.ToString(dgvRow.Cells["RowSeqNo"].Value);
            string strSQL = string.Empty;
            if (CvtFunc.ToDouble(strRecID) > 0)
            {
                if (MessageBox.Show("您确定要删除？", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DBAccess dbcon = new DBAccess(false, false);
                    try
                    {
                        dbcon.BeginTran();
                        strSQL = "Delete " + mstrTableName + " where RecID='" + strRecID + "'";
                        dbcon.ExecuteSql(strSQL);
                        dbcon.CommitTran(); 
                    
                        //string strWKProductID = CvtFunc.ToString(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WKProductID].Value);
                        //string strWKPriceType = CvtFunc.ToString(this.dgvInputDtl.CurrentRow.Cells[(int)DtlCol.WKPriceType].Value);
                        //strSQL = "select * from imCategoryWKWorkCost where WKProductID='" + strWKProductID + "' and WKPriceType='" + strWKPriceType + "'";
                        //DataTable dtFind = dbcon.GetDataTable(strSQL);
                        //if (dtFind.Rows.Count > 0)
                        //{
                        //    if (MessageBox.Show("其他类别有相同的费用标准，是否也删除？", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                        //    {
                        //        foreach (DataRow drRow in dtFind.Rows)
                        //        {
                        //            strSQL = "Delete " + mstrTableName + " where RecID='" + drRow["RecID"] + "'";
                        //            dbcon.ExecuteSql(strSQL);
                        //        }
                        //    }
                        //}
                    }
                    catch (Exception ex)
                    {
                        dbcon.RollbackTran();
                    }
                    dbcon.CloseCon();
                }
            }
            return true;
        }
        private void dgvDetail_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            this.dgvInputDtl.EndEdit();

            if (e.ColumnIndex == (int)DtlCol.WorkerID)
            {
                string strErrMsg = string.Empty;
                if (CheckDtlRow(ref strErrMsg))
                {
                    Update_Detail(this.dgvInputDtl.Rows[e.RowIndex]);
                }
            }
          
            else if (e.ColumnIndex == (int)DtlCol.Qty)
            {
                this.dgvInputDtl.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = BaseFunctions.FormatNumeric(this.dgvInputDtl.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, "Ns.2");
            }
        }

        #endregion

        private void dgvInputDtl_Enter(object sender, EventArgs e)
        {
            if (!UpdateData())
            {
                txtWorkQty.Focus();
            }
            else
            {
                txtWorkingProcedureID.ReadOnly = true ; 
            }
        }

        private void btnAddLine_Click(object sender, EventArgs e)
        {
            
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (UpdateData())
            {
                ConfirmSalary();
                this.Close();
            }
        }

        private bool  ConfirmSalary()
        {
            using (DBAccess dbcon = new DBAccess(false, false))
            {
                dbcon.BeginTran();
                RMWorkQtyInputHdrDAL rmDAL = new RMWorkQtyInputHdrDAL();
                rmDAL.Confirm(dbcon, this.m_lRecId);  
                rmDAL.UpdateWorkerWorkSalary(dbcon, CvtFunc.ToDateTime(  udtWorkDate.Value), this.m_lRecId.ToString());
                dbcon.CommitTran(); 
                return true;
            }
        }

        private void btnPost_Click(object sender, EventArgs e)
        {
            using (DBAccess dbcon = new DBAccess(false, false))
            {
                if (ConfirmSalary())
                {
                    RMWorkQtyInputHdrDAL rmDAL = new RMWorkQtyInputHdrDAL();
                    if (rmDAL.Confirm(dbcon, this.m_lRecId))
                    {
                        rmDAL.Posted(dbcon, this.m_lRecId);
                    }
                }
            }
        }

        private void btnRecalWKUnitCost_Click(object sender, EventArgs e)
        {
            if (m_lRecId == 0) return;
            RMWorkQtyInputHdrDAL rmDAL = new RMWorkQtyInputHdrDAL();
            using (DBAccess dbcon = new DBAccess(false, false))
            {                
                string strHdrRecID = this.m_lRecId.ToString();  
                dbcon.BeginTran();
                if (!rmDAL.UpdateDetailUnitCost(dbcon, strHdrRecID))
                {
                    dbcon.RollbackTran();
                    return;
                }
                dbcon.CommitTran();

                MsgBoxEx.Show("更新完成!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

     
    }
}
